#include <benchmark/benchmark.h>
#include <sys/epoll.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include "util.h"

using namespace std;
struct epoll_event events[10], event;

static void Bm_function_Epoll_createl(benchmark::State &state)
{
    for (auto _ : state)
    {
        int epoll_fd = epoll_create1(0);
        if (epoll_fd == -1)
        {
            perror("epoll_createl");
            exit(EXIT_FAILURE);
        }
        benchmark::DoNotOptimize(epoll_fd);
        close(epoll_fd);
    }
    
    state.SetBytesProcessed(state.iterations());
}

static void Bm_function_Epoll_ctl(benchmark::State &state)
{
    int epoll_fd = epoll_create1(0);
    if (epoll_fd == -1)
    {
        perror("epoll_createl");
        exit(EXIT_FAILURE);
    }
    int fd = open("/dev/zero", O_RDONLY);
    if (fd == -1)
    {
        perror("open epoll_ctl");
        exit(EXIT_FAILURE);
    }
    event.events = EPOLLIN | EPOLLET;
    event.data.fd = fd;
    for (auto _ : state)
    {
        benchmark::DoNotOptimize(epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &event));
    }
    close(epoll_fd);

    state.SetBytesProcessed(state.iterations());
}

static void Bm_function_Epoll_wait(benchmark::State &state)
{
    int epoll_fd = epoll_create1(0);
    if (epoll_fd == -1)
    {
        perror("epoll_createl");
        exit(EXIT_FAILURE);
    }

    int fd = open("/dev/zero", O_RDONLY);
    if (fd == -1)
    {
        perror("open epoll_wait");
        exit(EXIT_FAILURE);
    }

    event.events = EPOLLIN | EPOLLET;
    event.data.fd = fd;
    for (auto _ : state)
    {
        epoll_wait(epoll_fd, events, 10, 0);
    }
    close(epoll_fd);
    state.SetBytesProcessed(state.iterations());
}

MUSL_BENCHMARK(Bm_function_Epoll_createl);
MUSL_BENCHMARK(Bm_function_Epoll_ctl);
MUSL_BENCHMARK(Bm_function_Epoll_wait);
